package com.swgk.core.util;

import com.google.gson.Gson;
import com.swgk.core.base.model.entity.ErrorEntity;

import retrofit2.HttpException;

/**
 * Description:
 * Author zhengkewen
 * Time 2018/3/13
 */
public class HttpErrorUtil {

    public static final String HTTP_401 = "401"; //token失效

    public static String getServerErrorMsg(Throwable throwable) {
        if (throwable instanceof HttpException) {
            HttpException error = (HttpException) throwable;
            try {
                String response = error.response().errorBody().string();
                if (response.equals("")) {
                    return "";
                }
                ErrorEntity errorEntity = new Gson().fromJson(response,
                        ErrorEntity.class);
                return errorEntity.getMessage();
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
        }
        return "";
    }

    public static boolean isHttpException(Throwable throwable) {
        if (throwable instanceof HttpException) {
            return true;
        }
        return false;
    }

    public static boolean isNetException(Throwable throwable) {
        if (throwable instanceof java.net.ConnectException) {
            return true;
        }
        return false;
    }

    public static String getHttpErrorMsg(Throwable throwable) {
        String msg = "";
        try {
            HttpException error = (HttpException) throwable;
            int code = error.code();
            switch (code) {
                case 404:
                    msg = "服务器异常,请稍后再试";
                    break;
                case 401:
                    msg = HTTP_401;
                    break;
            }
        } catch (Exception e) {
            msg = "应用压力太大出问题了,请联系我们进行修复...";
        }
        return msg;
    }
}
